package com.gitee.zihaolicn;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.comments.Comment;

import java.io.File;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Paths;

public class RemoveComments {
    public static void main(String[] args) {
        // 输入和输出文件路径
        String inputFilePath = "C:\\Users\\li003\\IdeaProjects\\RepoJavaDecompile\\src\\main\\java\\com\\gitee\\zihaolicn\\RemoveComments.java";
        String outputFilePath = "C:\\Users\\li003\\IdeaProjects\\RepoJavaDecompile\\src\\main\\java\\com\\gitee\\zihaolicn\\RemoveCommentsNoComment.java";

        try {
            // 读取 Java 文件
            String sourceCode = new String(Files.readAllBytes(Paths.get(inputFilePath)));

            // 解析 Java 代码为 AST
            CompilationUnit cu = StaticJavaParser.parse(sourceCode);

            // 移除所有注释（包括行注释、块注释和 Javadoc）
            cu.getAllComments().forEach(Comment::remove);

            // 确保输出目录存在
            File outputFile = new File(outputFilePath);
            Files.createDirectories(Paths.get(outputFile.getParent()));

            // 将修改后的代码写入输出文件
            try (FileWriter writer = new FileWriter(outputFile)) {
                writer.write(cu.toString());
            }

            System.out.println("Comments removed successfully. Output written to: " + outputFilePath);

        } catch (Exception e) {
            System.err.println("Error processing file: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
